from elasticsearch import Elasticsearch
import  ih2torrent
class elasticsearch_data():
    def __init__(self,host='localhost'):
        # 初始化ini操作脚本，获取配置文件
        self.es=Elasticsearch(host)

    def str_list(self, data):
        h = data.split()
        q = []
        w = []
        e = []
        for i in h:
            z = i.split(',')
            for k in z:
                q.append(k)
        for x in q:
            c = x.split('.')
            for k in c:
                w.append(k)
        for v in w:
            b = v.split(':')
            for k in b:
                e.append(k)
        return e

    def query_data(self,keywords_list):
        """

        :param keywords_list:  关键字词，数组
        :param name: 查询ES中的doc
        :return:
        """
        query_data = {
            "query": {
                "multi_match": {
                    "query": keywords_list,
                    "type": "best_fields",
                    "minimum_should_match": "50%",
                    "fields": ['files_name','files_dict' ]
                }
            },
            "from": 0,
            "size": 100
        }

        return query_data




    # 从es获取数据
    def get_datas_by_query(self,index_name,types,keywords):
        '''
        :param index_name: 索引名称
        :param keywords: 关键字词，数组
        :param name: 需要数据条件，例如title
        :return: all_datas 返回查询到的所有数据（已经过param过滤）
        '''
        keywords = self.str_list(keywords)
        all_datas = []
        # 遍历所有的查询条件
        for keywords_list in keywords:
            # DSL语句
            query_data = self.query_data(keywords_list)
            res = self.es.search(
                index=index_name,
                doc_type=types,
                body=query_data
            )
        #     # for hit in res['hits']['hits']:
        #     #     # 获取指定的内容
        #     #     response = hit[param]
        #     #     # 添加所有数据到数据集中
        #     #     all_datas.append(response)
        # # 返回所有数据内容
        # dsl = {
        #     "query": {
        #         "match_all": {}
        #     },
        #
        # }
        # res = self.es.search(
        #     index=index_name,
        #     doc_type=types,
        #     body=dsl
        # )
        return res

    def query_all_data(self,index_name,types):

        dsl = {
            "query": {
                "match_all": {}
            },

        }
        res = self.es.search(
            index=index_name,
            doc_type=types,
            body=dsl
        )
        return res


    # # 当索引不存在创建索引
    # def create_index(self,index_name):
    #     '''
    #     :param index_name: 索引名称
    #     :return:如果创建成功返回创建结果信息，试过已经存在创建新的index失败返回index的名称
    #     '''
    #     # 获取索引的映射
    #     # index_mapping = IndexMapping.index_mapping
    #     # # 判断索引是否存在
    #     # if self.es.indices.exists(index=index_name) is not True:
    #     #     # 创建索引
    #     #     res = self.es.indices.create(index=index_name,body=index_mapping)
    #     #     # 返回结果
    #     #     return res
    #     # else:
    #     #     # 返回索引名称
    #     #     return index_name
    #     pass

    # 从ES中在指定的索引中删除指定数据（根据id判断）
    def delete_data_by_id(self,index_name,doc_type,id):
        '''
        :param index_name: 索引名称
        :param index_type: 文档类型
        :param id: 唯一标识id
        :return: 删除结果信息
        '''
        res = self.es.delete(index=index_name,doc_type=doc_type,id=id)
        return res

    # 根据条件删除数据
    def delete_data_by_query(self,index_name,doc_type,param,name):
        '''
        :param index_name:索引名称，为空查询所有索引
        :param doc_type:文档类型，为空查询所有文档类型
        :param param:过滤条件值
        :param name: 查询ES中的doc
        :return:执行条件删除后的结果信息
        '''
        # DSL语句
        query_data = {
            "query": {
                "multi_match": {
                    "query": param,
                    "analyze_wildcard": True,
                    "type": "best_fields",
                    "minimum_should_match": "50%",
                    "fields": [name, ]

                }
            }
        }
        res = self.es.delete_by_query(index=index_name,doc_type=doc_type,body=query_data,_source=True)
        return res


